package com.ztjava.common.tool.files;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.util.Auth;
import com.xiaoleilu.hutool.date.DateUtil;
import com.ztjava.common.Common;
import com.ztjava.core.Constant;
import com.ztjava.core.Jsub;
import com.ztjava.core.tool.ViewTool;
import com.ztjava.core.utiliy.StringUtil;

public class QiniuTool {
	private static Logger logger = Logger.getLogger(QiniuTool.class);
	/***
	 * 初始化检查
	 */
	public static boolean initCheck(){
		Cache cache = Redis.use();
		if(!cache.hexists(Constant.R_PARAM, Common.COMMON_FILES_QINIU_ACCESSKEY)){
			logger.error("缺少COMMON_FILES_QINIU_ACCESSKEY参数配置！");
			return false;
		}
		if(!cache.hexists(Constant.R_PARAM, Common.COMMON_FILES_QINIU_SECRETKEY)){
			logger.error("缺少COMMON_FILES_QINIU_SECRETKEY参数配置！");
			return false;
		}
		if(!cache.hexists(Constant.R_PARAM, Common.COMMON_FILES_QINIU_BUCKET)){
			logger.error("缺少COMMON_FILES_QINIU_BUCKET参数配置！");
			return false;
		}
		if(!cache.hexists(Constant.R_PARAM, Common.COMMON_FILES_QINIU_CDN)){
			logger.error("缺少COMMON_FILES_QINIU_CDN参数配置！");
			return false;
		}
		return true;
	}
	/***
	 * 删除文件
	 * @param key
	 */
	public static void deleteFile(String key){
		if(key.startsWith("/")) key = key.substring(1,key.length());
		Configuration cfg = new Configuration(Zone.zone0());
		String accessKey = ViewTool.param(Common.COMMON_FILES_QINIU_ACCESSKEY);
		String secretKey = ViewTool.param(Common.COMMON_FILES_QINIU_SECRETKEY);
		String bucket = ViewTool.param(Common.COMMON_FILES_QINIU_BUCKET);
		Auth auth = Auth.create(accessKey, secretKey);
		BucketManager bucketManager = new BucketManager(auth, cfg);
		try {
		    bucketManager.delete(bucket, key);
		    logger.debug("七牛文件删除成功:"+key);
		} catch (QiniuException ex) {
			logger.error("七牛文件删除失败："+ex.code());
			logger.error(key);
			logger.error(ex.response.toString());
		}
	}
	
	/***
	 * 七牛文件上传
	 * @param file
	 * @param directory
	 * @param user_id
	 * @return
	 */
	public static String postFile(File file,String directory,Integer user_id){
		String accessKey = ViewTool.param(Common.COMMON_FILES_QINIU_ACCESSKEY);
		String secretKey = ViewTool.param(Common.COMMON_FILES_QINIU_SECRETKEY);
		String bucket = ViewTool.param(Common.COMMON_FILES_QINIU_BUCKET);
		
		
		String key = Jsub.folder+"/"+directory + "/"+DateUtil.format(new Date(),"yyyyMM") 
				+ "/"+user_id+"/"+StringUtil.getRandomString(18);
		Auth auth = Auth.create(accessKey, secretKey);
		String token = auth.uploadToken(bucket,key);
		
		RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
		
		RequestBody requestBody = new MultipartBody.Builder()
			.addFormDataPart("file", file.getName(), fileBody)
			.addFormDataPart("key",key)
			.addFormDataPart("token",token)
			.setType(MediaType.parse("multipart/form-data"))
			.build();
		
		Request requestPostFile = new Request.Builder()
        	.url("http://upload.qiniu.com/")
        	.post(requestBody)
        	.build();
		
		OkHttpClient client = new OkHttpClient.Builder()
	        .connectTimeout(10, TimeUnit.SECONDS)
	        .readTimeout(10, TimeUnit.SECONDS)
	        .build();
		
		client.newCall(requestPostFile).enqueue(new Callback() {
			@Override
			public void onResponse(Call call, Response response) throws IOException {
				logger.debug("七牛服务器文件上传反馈：" +response.body().string());
			}
			@Override
			public void onFailure(Call call, IOException e) {
				logger.error("七牛服务器上传文件失败："+e.getMessage());
				e.printStackTrace();
			}
		});
		return key;
	}
}
